package com.sxj.corejava.code15_反射;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test05_操作方法 {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 1.获取当前类以及其祖宗类(父类、父类的父类...)中被public修饰的方法
        Class c = User.class;
        Method[] methods = c.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("******************************");

        // 2.获取当前类中所有方法
        methods = c.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("******************************");

        // 3.获取当前类以及其祖宗类中指定public修饰的方法
        Method showMethod = c.getMethod("show01");
        System.out.println(showMethod);
        Method testMethod = c.getMethod("test01", String.class);
        System.out.println(testMethod);

        // 4.获取当前类中指定方法,不区分修饰符
        Method showMethod2 = c.getDeclaredMethod("show02");
        System.out.println(showMethod2);
        Method showMethod3 = c.getDeclaredMethod("show03");
        System.out.println(showMethod3);
        Method showMethod4 = c.getDeclaredMethod("show04");
        System.out.println(showMethod4);
        // 无法访问父类的
//        Method testMethod2 = c.getDeclaredMethod("test02");
//        System.out.println(testMethod2);
        System.out.println("******************************");

        // Method对象方法
        // 1.获取方法名
        System.out.println(showMethod.getName());

        // 2.执行方法
        User user = new User();
        // invoke(Object obj,Object... args)
        // 参数一:方法所在的对象是谁
        // 参数二:方法的实际参数
        showMethod.invoke(user);

        Method addMethod = c.getDeclaredMethod("add", int.class, int.class);
        System.out.println(addMethod);

        int sum = (int) addMethod.invoke(user, 2, 3);
        System.out.println(sum);

        showMethod4.setAccessible(true);
        showMethod4.invoke(user);
    }

}
